package br.edu.catolica.sadbc.core.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Crypto {
	
	private static MessageDigest algorithm = null;
	
	private static Crypto instance = null;
	
	private Crypto() {
		
	}
	
	public static Crypto instance() {
		if (instance == null) {
			instance = new Crypto();
		}
		return instance;
	}
	
	public String encoding(String value, String salt) {
		if (salt != null && salt.equals("")) {
			return encoding(value + salt);
		}
		return encoding(value);
	}
	
	
	public String encoding(String value) {
		if (value == null) {
			return null;
		}
		
        byte messageDigest[];
		try {
			messageDigest = getMessageDigest().digest(value.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
        
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
        	hexString.append(String.format("%02X", 0xFF & b));
        }
        
        return hexString.toString();
	}
	
	private MessageDigest getMessageDigest() {
		try {
			if (algorithm == null) {
				algorithm = MessageDigest.getInstance("SHA-256");
			}
		} catch (NoSuchAlgorithmException e) {
		}
		
		return algorithm;
	}

}
